import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView, Input, Image, Button } from '@tarojs/components';
import send from '../../../assets/icon/send.svg';
import moveBottom from '../../../assets/icon/move-bottom.svg';
import Taro, { usePageScroll } from '@tarojs/taro';
import { chatApi } from '../../../services/chatApi';
import { Loading, Loading1, Received } from '@nutui/icons-react-taro';
import { Button as ButtonNut } from '@nutui/nutui-react-taro';
import towxml from '../../../towxml/towxml';
import * as TextEncoding from 'text-encoding-shim'
import './index.scss';

const AIAssist = () => {
  const { router } = Taro.getCurrentInstance();
  const assigneeId = router.params.assigneeId;
  const [messages, setMessages] = useState([]);
  const [loading, setLoading] = useState(true);
  const [inputValue, setInputValue] = useState('');
  const [isOpenType, setIsOpenType] = useState(false);
  const [newMessage, setNewMessage] = useState('');
  const [showScrollButton, setShowScrollButton] = useState(false);

  // 获取消息历史
  useEffect(() => {
    setLoading(true);
    chatApi.getHistory(assigneeId).then(res => {
      console.log(res);
      if (res && res.messages) {
        // 处理消息，确保role=='user'的消息设置为isUser=true
        const processedMessages = res.messages.map(msg => ({
          ...msg,
          isUser: msg.role === 'user'
        }));
        setMessages(processedMessages);
      }
      setLoading(false);
      // 数据加载完成后滚动到底部
      setTimeout(scrollToBottom, 0);
    }).catch(err => {
      console.error(err);
      setLoading(false);
    });
  }, [assigneeId]);

  // 添加滚动到底部的方法
  const scrollToBottom = () => {
    Taro.createSelectorQuery()
      .select('#chat-history')
      .boundingClientRect(function (rect) {
        if (rect) {
          // 使页面滚动到底部
          Taro.pageScrollTo({
            scrollTop: rect.height,
            duration: 300
          })
        }
      }).exec()
  };

  // 消息变化时自动滚动到底部
  useEffect(() => {
    if (messages.length > 0) {
      setTimeout(scrollToBottom, 0);
    }
  }, [messages]);

  // 监听页面滚动事件
  useEffect(() => {
    // 计算是否在底部的函数
    const checkIfAtBottom = () => {
      Taro.createSelectorQuery()
        .select('#chat-history')
        .boundingClientRect(rectChat => {
          if (!rectChat) return;

          // 获取页面滚动位置
          Taro.createSelectorQuery()
            .selectViewport()
            .scrollOffset(scrollData => {
              const scrollTop = scrollData.scrollTop;
              const windowHeight = Taro.getSystemInfoSync().windowHeight;

              // 计算是否滚动到底部（考虑一定容差）
              const isAtBottom = scrollTop + windowHeight >= rectChat.height - 50;
              setShowScrollButton(!isAtBottom);
            }).exec();
        }).exec();
    };

    // 初始检查
    checkIfAtBottom();

    // 监听消息变化时也检查滚动状态
    if (messages.length > 0) {
      setTimeout(checkIfAtBottom, 100);
    }
  }, [messages]);

  // 使用usePageScroll钩子监听页面滚动
  usePageScroll(() => {
    Taro.createSelectorQuery()
      .select('#chat-history')
      .boundingClientRect(rectChat => {
        if (!rectChat) return;

        Taro.createSelectorQuery()
          .selectViewport()
          .scrollOffset(scrollData => {
            const scrollTop = scrollData.scrollTop;
            const windowHeight = Taro.getSystemInfoSync().windowHeight;

            const isAtBottom = scrollTop + windowHeight >= rectChat.height - 50;
            setShowScrollButton(!isAtBottom);
          }).exec();
      }).exec();
  });

  // 提取最后一个data JSON对象
  const extractLastDataJson = (dataStr) => {
    // 使用正则表达式找到所有的data: {...} 格式的字符串，确保是行首的data:前缀
    const dataRegex = /^data:\s*({.*?})$/gm;
    let match;
    let lastData = null;

    while ((match = dataRegex.exec(dataStr)) !== null) {
      try {
        lastData = JSON.parse(match[1]);
      } catch (e) {
        console.error('Error parsing JSON:', e);
      }
    }

    return lastData;
  };

  const handleSend = () => {
    if (!inputValue.trim()) return;

    const userMessage = {
      content: inputValue,
      isUser: true
    };

    // 立即添加用户消息到界面并清空输入框
    setInputValue('');
    setMessages([...messages, userMessage]);
    setLoading(true);
    setNewMessage('');
    setIsOpenType(true);

    // 发送到服务器
    const requestTask = chatApi.sendMessage(inputValue, assigneeId)
    requestTask.onChunkReceived(res => {
      const str = new TextEncoding.TextDecoder('utf-8').decode(new Uint8Array(res.data));
      // 因为返回的流式数据是整块，所以需要提取最后一个data JSON对象
      const json = extractLastDataJson(str);
      if (json.content) {
        setNewMessage(json.content);
      } else if (json.final_content) {
        setNewMessage(json.final_content);
        setIsOpenType(false);
        // 将AI回复添加到消息历史
        setMessages(prevMessages => [
          ...prevMessages,
          {
            content: json.final_content,
            isUser: false
          }
        ]);
        setLoading(false);
      }
    });
  };

  // 添加复制到发布任务页面的方法
  const copyToTaskPage = (content) => {
    // 保存消息内容到本地存储，以便在发布任务页面获取
    Taro.setStorageSync('taskContent', content);

    // 导航到发布任务页面
    Taro.navigateTo({
      url: '/package-manage/pages/task-create/index'
    });
  };

  return (
    <View className='ai-assist'>
      <ScrollView
        className='chat-history'
        scrollY={true}
        scrollWithAnimation={true}
        scrollIntoView="msg-bottom"
        id="chat-history"
      >
        {messages.length > 0 ? (
          <>
            {messages.map((message, index) => (
              message.isUser ? (
                <View className='message-container-user' key={index}>
                  <View className='chat-bubble-user'>
                    <Text>{message.content}</Text>
                  </View>
                </View>
              ) : (
                <View className='message-container' key={index}>
                  <View className='chat-bubble-ai'>
                    <towxml mdText={{ text: message.content }} openTyper={false} />
                  </View>
                  <ButtonNut
                    type="success"
                    icon={<Received color="#fff" />}
                    onClick={() => copyToTaskPage(message.content)}
                  >
                    复制到任务
                  </ButtonNut>
                </View>
              )
            ))}

            {/* 显示正在接收的新消息 */}
            {isOpenType && (
              <View className='message-container'>
                <View className='chat-bubble-ai'>
                  <towxml mdText={{ text: newMessage }} openTyper={true} speed={3} />
                  <Loading />
                </View>
              </View>
            )}
            {/* 用于滚动到底部的空元素 */}
            <View id="msg-bottom"></View>
          </>
        ) : (
          <View className='welcome-container'>
            <View className='welcome-card'>
              <View className='welcome-header'>
                <Text className='welcome-title'>欢迎使用AI学习助手</Text>
              </View>
              <View className='welcome-avatar'>
                <View className='avatar-circle'>
                  <Text>点</Text>
                </View>
              </View>
              <View className='welcome-content'>
                <Text className='welcome-text'>您好，我是您的AI学习助手！</Text>
                <View className='welcome-features'>
                  <View className='feature-item'>
                    <Text className='feature-text'>✓ 提供个性化学习建议</Text>
                  </View>
                  <View className='feature-item'>
                    <Text className='feature-text'>✓ 解答学习过程中的问题</Text>
                  </View>
                  <View className='feature-item'>
                    <Text className='feature-text'>✓ 定制学习计划与内容</Text>
                  </View>
                </View>
                <Text className='start-hint'>请在下方输入您的问题开始对话</Text>
              </View>
            </View>
          </View>
        )}
      </ScrollView>

      {/* 滚动到底部按钮 */}
      {messages.length > 0 && showScrollButton && (
        <View
          className='chat-send-button scroll-to-bottom-button'
          onClick={scrollToBottom}
        >
          <Image src={moveBottom} />
        </View>
      )}

      <View className='chat-input-container'>
        <Input
          className='chat-input'
          placeholder='输入消息...'
          value={inputValue}
          onInput={e => setInputValue(e.detail.value)}
          onConfirm={handleSend}
        />
        <View
          className={`chat-send-button ${(loading || !inputValue.trim()) ? 'disabled' : ''}`}
          onClick={() => {
            if (!loading && inputValue.trim()) {
              handleSend();
            }
          }}
        >{loading ? <Loading1 /> : <Image src={send} />}

        </View>
      </View>
    </View>
  );
};

export default AIAssist;
